/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.npmpackage.core.service;

import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.utility.ResourceLocalizeUtil;
import com.inspur.edp.web.npmpackage.api.constant.I18nMsgConstant;
import com.inspur.edp.web.npmpackage.api.entity.NpmInstallParameter;
import com.inspur.edp.web.npmpackage.api.entity.NpmPackageCheckUpdateOptions;
import com.inspur.edp.web.npmpackage.api.entity.NpmPackageResponse;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmRepository;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmSettings;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmUpdatePolicy;
import com.inspur.edp.web.npmpackage.api.service.NpmPackageService;
import com.inspur.edp.web.npmpackage.core.npminstall.NodeModulesPathGenerator;
import com.inspur.edp.web.npmpackage.core.npmpackagecheck.NpmPackageCheck;
import com.inspur.edp.web.npmpackage.core.npmsetting.NpmSettingManager;

/**
 * npm 包 manager service
 *
 * @author guozhiqi
 */
public class NpmPackageServiceImpl implements NpmPackageService {
    /**
     * 检测是否发生npm包变化
     * @return
     */
    public NpmPackageResponse checkUpdate() {
        NpmSettings npmSettings = NpmSettingManager.getNpmSetting(false);
        // 如果为离线模式
        if (npmSettings.isOffline()) {
            NpmPackageResponse npmPackageResponse = new NpmPackageResponse();
            npmPackageResponse.setSuccess(true);
            npmPackageResponse.setErrorMessage(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0021));
            return npmPackageResponse;
        }

        NpmRepository currentRepository = null;
        NpmRepository[] repositories = npmSettings.getSettingConfig().getRepositories();
        for (NpmRepository repository : repositories) {
            String tempSettingMode = repository.getId();
            if (tempSettingMode.equals(npmSettings.getSettingMode())) {
                currentRepository = repository;
            }
        }
        if (currentRepository == null) {
            // 如果未找到当前配置的仓库
            NpmPackageResponse npmPackageResponse = new NpmPackageResponse();
            npmPackageResponse.setSuccess(true);
            npmPackageResponse.setErrorMessage(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0023));
            return npmPackageResponse;
        }

        // 如果配置策略为手工或从不
        if (NpmUpdatePolicy.never.equals(currentRepository.getUpdatePolicy())) {
            NpmPackageResponse npmPackageResponse = new NpmPackageResponse();
            npmPackageResponse.setSuccess(true);
            npmPackageResponse.setErrorMessage(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0024));
            return npmPackageResponse;
        }

        if (NpmUpdatePolicy.manual.equals(currentRepository.getUpdatePolicy())) {
            NpmPackageCheckUpdateOptions checkUpdateOptions = new NpmPackageCheckUpdateOptions();
            checkUpdateOptions.setExecuteEnvironment(ExecuteEnvironment.Design);
            checkUpdateOptions.setUpgradeTool(false);
            return this.checkUpdate(checkUpdateOptions);
        }
        // 如果为编译前 那么自动执行无需提示
        return NpmPackageResponse.create();
    }

    /**
     * 执行npm 版本检测
     *
     * @param checkUpdateOptions
     * @return
     */
    public NpmPackageResponse checkUpdate(NpmPackageCheckUpdateOptions checkUpdateOptions) {

        // 升级工具中不进行检测
        if (checkUpdateOptions.isUpgradeTool()) {
            NpmPackageResponse npmPackageResponse = new NpmPackageResponse();
            npmPackageResponse.setSuccess(true);
            npmPackageResponse.setErrorMessage(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0025));
            return npmPackageResponse;
        }

        String currentServerPath = FileUtility.getCurrentWorkPath(checkUpdateOptions.isUpgradeTool());


        // 判断是否存在node_modules 避免被误删除的情况
        NpmInstallParameter npmInstallParameter = new NpmInstallParameter();
        npmInstallParameter.setExecuteEnvironment(checkUpdateOptions.getExecuteEnvironment());
        npmInstallParameter.setMobile(checkUpdateOptions.isMobile());
        String nodeModulesPath = NodeModulesPathGenerator.generatePackageJsonPath(npmInstallParameter, currentServerPath);
        nodeModulesPath = FileUtility.combine(nodeModulesPath, "node_modules");
        if (!FileUtility.exists(nodeModulesPath) || FileUtility.isEmptyFolder(nodeModulesPath)) {
            String tip = ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0026, nodeModulesPath);
            WebLogger.Instance.info(tip, NpmPackageServiceImpl.class.getName());
            return NpmPackageResponse.createError(tip);
        }

        // 是否需要update标识
        boolean npmCheckFlag = NpmPackageCheck.check(checkUpdateOptions);


        if (npmCheckFlag) {
            return NpmPackageResponse.create();
        } else {
            return NpmPackageResponse.createError(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0027));
        }
    }
}
